package org.ehe.erp.service.quality.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.BeanUtils;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.ehe.business.bom.domain.BomMaster;
import org.ehe.business.bom.service.BomMasterService;
import org.ehe.business.project.service.ProjectService;
import org.ehe.common.core.utils.MapstructUtils;
import org.ehe.common.mybatis.core.page.PageQuery;
import org.ehe.common.mybatis.core.page.TableDataInfo;
import org.ehe.common.satoken.utils.LoginHelper;
import org.ehe.erp.domain.product.bo.ErpProductBo;
import org.ehe.erp.domain.product.vo.ErpProductVo;
import org.ehe.erp.domain.quality.ErpQualityFeedback;
import org.ehe.erp.domain.quality.ErpQualityRecord;
import org.ehe.erp.domain.quality.ErpQualityTask;
import org.ehe.erp.domain.quality.bo.ErpQualityFeedbackBo;
import org.ehe.erp.domain.quality.bo.ErpQualityRecordBo;
import org.ehe.erp.domain.quality.dto.QualityRecordQueryDto;
import org.ehe.erp.domain.quality.vo.ErpQualityAttachmentVo;
import org.ehe.erp.domain.quality.vo.ErpQualityFeedbackVo;
import org.ehe.erp.domain.quality.vo.ErpQualityRecordVo;
import org.ehe.erp.mapper.quality.ErpQualityFeedbackMapper;
import org.ehe.erp.mapper.quality.ErpQualityRecordMapper;
import org.ehe.erp.mapper.quality.ErpQualityTaskMapper;
import org.ehe.erp.service.product.IErpProductService;
import org.ehe.erp.service.quality.ErpQualityAttachmentService;
import org.ehe.erp.service.quality.ErpQualityFeedbackService;
import org.ehe.erp.service.quality.ErpQualityRecordService;
import org.ehe.erp.service.quality.ErpQualityTaskService;
import org.ehe.system.domain.vo.SysUserVo;
import org.ehe.system.service.ISysUserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

/**
 * 质检记录信息
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ErpQualityRecordServiceImpl extends ServiceImpl<ErpQualityRecordMapper, ErpQualityRecord>
    implements ErpQualityRecordService {

    private final ErpQualityTaskMapper taskMapper;
    private final ErpQualityRecordMapper baseMapper;
    private final ErpQualityFeedbackMapper feedbackMapper;
    private final ErpQualityFeedbackService feedbackService;
    private final ErpQualityAttachmentService attachmentService;
    private final BomMasterService masterService;
    private final IErpProductService productService;
    private final ISysUserService userService;

    /**
     * 分页
     * @param dto
     * @param pageQuery
     * @return
     */
    @Override
    public TableDataInfo<ErpQualityRecordVo> queryPageList(QualityRecordQueryDto dto, PageQuery pageQuery) {
        LambdaQueryWrapper<ErpQualityRecord> wrapper = buildWrapper(dto);
        IPage<ErpQualityRecordVo> page = baseMapper.selectVoPage(pageQuery.build(), wrapper);
        for (ErpQualityRecordVo record : page.getRecords()) {
            Long taskId = record.getTaskId();
            ErpQualityTask task = taskMapper.selectById(taskId);
            if(Objects.nonNull(task)){
                record.setOrderNo(task.getOrderNo());
                BomMaster bom = masterService.getById(task.getBomId());
                if(Objects.nonNull(bom)){
                    record.setBomName(bom.getBomName());
                    record.setBomCode(bom.getBomCode());
                }
                ErpProductBo productBo = new ErpProductBo();
                productBo.setId(record.getProductId());
                TableDataInfo<ErpProductVo> erpProductVoTableDataInfo = productService.queryPageList(productBo, pageQuery);
                if(Objects.nonNull(erpProductVoTableDataInfo)){
                    record.setProductVo(erpProductVoTableDataInfo.getRows().get(0));
                }
            }
        }
        return TableDataInfo.build(page);
    }

    /**
     * 查询全部
     * @param dto
     * @return
     */
    @Override
    public List<ErpQualityRecordVo> queryList(QualityRecordQueryDto dto) {
        List<ErpQualityRecordVo> recordVos = baseMapper.selectVoList(buildWrapper(dto));
        for (ErpQualityRecordVo record : recordVos) {
            Long taskId = record.getTaskId();
            ErpQualityTask task = taskMapper.selectById(taskId);
            if(Objects.nonNull(task)){
                record.setOrderNo(task.getOrderNo());
                BomMaster bom = masterService.getById(task.getBomId());
                if(Objects.nonNull(bom)){
                    record.setBomName(bom.getBomName());
                    record.setBomCode(bom.getBomCode());
                }
                ErpProductBo productBo = new ErpProductBo();
                productBo.setId(record.getProductId());
                TableDataInfo<ErpProductVo> erpProductVoTableDataInfo = productService.queryPageList(productBo, new PageQuery(1, 10));
                if(Objects.nonNull(erpProductVoTableDataInfo)){
                    record.setProductVo(erpProductVoTableDataInfo.getRows().get(0));

                }
            }
        }

        return recordVos;
    }

    /**
     * 查看详情
     * @param id
     * @return
     */
    @Override
    public ErpQualityRecordVo queryById(Long id) {
        ErpQualityRecordVo erpQualityRecordVo = baseMapper.selectVoById(id);
        if(erpQualityRecordVo.getCheckResult() == 0){
            List<ErpQualityFeedbackVo> feedbacks = feedbackMapper.selectVoList(new LambdaQueryWrapper<ErpQualityFeedback>()
                .eq(ErpQualityFeedback::getRecordId, erpQualityRecordVo.getId()));
            //反馈附件
            if(CollectionUtils.isNotEmpty(feedbacks)){
                feedbacks.forEach(f->{
                    List<ErpQualityAttachmentVo> attachmentVoList = attachmentService.listByFeedbackId(f.getId());
                    f.setAttachmentVoList(attachmentVoList);
                });
            }
            erpQualityRecordVo.setFeedbackVos(feedbacks);
        }
        //BOM信息
        ErpQualityTask task = taskMapper.selectById(erpQualityRecordVo.getTaskId());
        if (Objects.nonNull(task)) {
            BomMaster bom = masterService.getById(task.getBomId());
            if(Objects.nonNull(bom)){
                erpQualityRecordVo.setBomName(bom.getBomName());
                erpQualityRecordVo.setBomCode(bom.getBomCode());
            }
        }
        //产品信息
        ErpProductBo productBo = new ErpProductBo();
        productBo.setId(erpQualityRecordVo.getProductId());
        TableDataInfo<ErpProductVo> erpProductVoTableDataInfo = productService.queryPageList(productBo, new PageQuery(1,10));
        if(Objects.nonNull(erpProductVoTableDataInfo)){
            erpQualityRecordVo.setProductVo(erpProductVoTableDataInfo.getRows().get(0));
        }
        return erpQualityRecordVo;
    }

    /**
     * 保存
     * @param bo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertByBo(ErpQualityRecordBo bo) {
        ErpQualityRecord entity = BeanUtil.toBean(bo, ErpQualityRecord.class);
        if (entity.getCheckTime() == null) {
            entity.setCheckTime(LocalDateTime.now());
        }
        int id = baseMapper.insert(entity);
        //不合格的时候
        if (bo.getCheckResult() == 0) {
            ErpQualityFeedbackBo feedbackBo = bo.getFeedbackBo();
            feedbackBo.setFeedbackNo(feedbackService.generateFeedbackNo());
            feedbackBo.setTaskId(bo.getTaskId());
            feedbackBo.setRecordId(entity.getId());
            feedbackBo.setStatus(0); //待处理
            feedbackBo.setFeedbackPersonId(LoginHelper.getUserId());
            SysUserVo sysUserVo = userService.selectUserById(LoginHelper.getUserId());
            feedbackBo.setFeedbackPerson(sysUserVo.getNickName());
            feedbackService.insertByBo(feedbackBo);
            //反馈附件
            if(CollectionUtils.isNotEmpty(bo.getQualityAttachmentList())){
                bo.getQualityAttachmentList().forEach(a->{
                    a.setFeedbackId((long) feedbackBo.getId());
                    a.setRecordId((long) id);
                    a.setUploadPerson(LoginHelper.getUsername());
                    a.setTenantId(LoginHelper.getTenantId());
                    a.setUploadTime(LocalDateTime.now());
                    attachmentService.save(a);
                });
            }
        }
        return true;
    }

    /**
     * 修改
     * @param bo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateByBo(ErpQualityRecordBo bo) {
        ErpQualityRecord entity = BeanUtil.toBean(bo, ErpQualityRecord.class);
        if (entity.getCheckTime() == null) {
            entity.setCheckTime(LocalDateTime.now());
        }
        return baseMapper.updateById(entity) > 0;
    }

    /**
     * 删除
     * @param ids
     * @param isValid
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            // 如需校验可在此扩展
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    /**
     * 根据taskId获取信息
     * @param taskId
     * @return
     */
    @Override
    public List<ErpQualityRecordVo> getByTaskId(Long taskId) {
        return baseMapper.selectVoList(
            Wrappers.<ErpQualityRecord>lambdaQuery()
                .eq(ErpQualityRecord::getTaskId, taskId)
                .orderByDesc(ErpQualityRecord::getCreateTime));
    }

    /**
     * 批量保存
     * @param bos
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean batchInsert(List<ErpQualityRecordBo> bos) {
        List<ErpQualityRecord> list = BeanUtil.copyToList(bos, ErpQualityRecord.class);
        list.forEach(r -> {
            if (r.getCheckTime() == null) r.setCheckTime(LocalDateTime.now());
        });
        return saveBatch(list);
    }

    /**
     * 构建查询条件
     * @param dto
     * @return
     */
    private LambdaQueryWrapper<ErpQualityRecord> buildWrapper(QualityRecordQueryDto dto) {
        LambdaQueryWrapper<ErpQualityRecord> w = Wrappers.lambdaQuery();
        w.eq(ObjectUtil.isNotNull(dto.getTaskId()), ErpQualityRecord::getTaskId, dto.getTaskId());
        w.eq(ObjectUtil.isNotNull(dto.getProductId()), ErpQualityRecord::getProductId, dto.getProductId());
        w.like(StringUtils.isNotBlank(dto.getItemName()), ErpQualityRecord::getItemName, dto.getItemName());
        w.eq(ObjectUtil.isNotNull(dto.getCheckResult()), ErpQualityRecord::getCheckResult, dto.getCheckResult());
        w.like(StringUtils.isNotBlank(dto.getCheckPerson()), ErpQualityRecord::getCheckPerson, dto.getCheckPerson());
        if (dto.getCheckTimeStart() != null) w.ge(ErpQualityRecord::getCheckTime, dto.getCheckTimeStart());
        if (dto.getCheckTimeEnd() != null) w.le(ErpQualityRecord::getCheckTime, dto.getCheckTimeEnd());
        w.orderByDesc(ErpQualityRecord::getCreateTime);
        return w;
    }

    /**
     * 获取未质检的信息
     * @param taskId
     * @return
     */
    @Override
    public List<ErpQualityRecordVo> queryNoCheckList(Long taskId) {
        return this.baseMapper.selectVoList(new LambdaQueryWrapper<ErpQualityRecord>()
            .eq(ErpQualityRecord::getTaskId,taskId)
            //.eq(ErpQualityRecord::getCheckResult,0)
        );
    }
}
